import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:jydoctorflutter/model/web_model.dart';
import 'package:jydoctorflutter/pages/login/send_code/logic.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../generated/assets.dart';
import 'LoginVC.dart';

class obtainTicketWebPage extends StatefulWidget {
  final con =
  WebViewController()..setJavaScriptMode(JavaScriptMode.unrestricted);
  obtainTicketWebPage({super.key});

  @override
  State<obtainTicketWebPage> createState() => _obtainTicketWebPageState();
}

class _obtainTicketWebPageState extends State<obtainTicketWebPage> {
  @override
  
  void initState() {

    // TODO: implement initState
    super.initState();

    widget.con
      ..addJavaScriptChannel('setCodeKey', onMessageReceived: ( message) async{
        print('99999');
        print(message.message);
        WebModel model = WebModel.fromJson(jsonDecode(message.message));
        print(model.ticket);
        Get.find<SendCodeLogic>().ticketStr.value = '${model.ticket}' ;
        Get.find<SendCodeLogic>().randstr.value = '${model.randstr}' ;// 更新结果
        Get.back(); //
      })
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress:
              (progress) =>
              print('=============== Loading progress: $progress%'),
          onHttpError: (error) => {
            print('=============== error : $error'),
          },
          onPageStarted: (url) => print('=============== Page started: $url'),

          onPageFinished: (url) async {
            await widget.con.runJavaScript(
              "window.location.hash = '#/policy';",
            );
          },
          onNavigationRequest: (request) {
            print('=============== Navigating to: ${request.url}');
            return NavigationDecision.navigate;
          },
        ),
      )

    ..loadRequest(Uri.parse('https://web-codes.grdoc.org/#/appCode'));
    // ..loadHtmlString("${Assets.htmlIndex}#/policy");
    //   ..loadFlutterAsset(Assets.ticketKey)

  }

  @override
  void dispose() {
    widget.con.clearCache(); // 清理缓存
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(

        color:Colors.yellow,
        child: WebViewWidget(controller: widget.con),

      ),
    );
  }
}
